﻿module Sustainalytics.EsgRatings {

    import Common = Sustainalytics.Common;
    import Company = Sustainalytics.Company;
    import Research = Sustainalytics.Research;
    import LRTM = Sustainalytics.LRTM;
    import Controversies = Sustainalytics.Controversies;

    export class EsgController extends Research.ResearchPageController {

        // currently active view
        public viewName: string;
        public selectedIndicator: KeyEsgIssueIndicatorDto;// selected indicator in the key ESG issues table on the analyst view 

        // whether current view is still loading
        public isInitLoading: boolean;

        // employee in charge with respective industry
        public industryLeadPersonnel: EsgIndustryLeadPersonnelDto;
        public $routeParams: any;

        public hasEsgResearch: boolean;
        public hasFocusRatings: boolean;
        public hasEsgUniverse: boolean = true;

        public noResearchMessage: string;
        public hasNoResearch: boolean = false;

        public hasControversiesResearch: boolean;
        public hasControversiesUniverse: boolean = true;        

        private userId: string;
        private accountId: string;
        private accountTier: number;
        private esgProfileId: string;

        constructor(
            private $rootScope: ng.IScope,
            protected $scope: Company.ICompanyBasedScope,
            protected $q: ng.IQService,
            protected $timeout: ng.ITimeoutService,
            protected $location: ng.ILocationService,
            protected RoutingService: Routing.IRoutingService,
            protected CompanyService: Company.ICompanyService,
            protected EsgIndustryLeadPersonnelService: IEsgIndustryLeadPersonnelService,
            protected NumberUtilityService: Common.NumberUtilityService,
            protected MostActiveReportService: MostActiveReports.MostActiveReportService,
            protected LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService,
            protected $modal: Common.IModal) {

            super($scope, $q, $location, RoutingService, CompanyService);

            var ctx = this;
            $scope['esg'] = ctx;
            ctx.$routeParams = ctx.RoutingService.getRouteParams();

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.userId = ctx.$rootScope['userInfo'].userId;
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.accountTier = ctx.$rootScope['userInfo'].accountTier;
            ctx.esgProfileId = ctx.$rootScope['userInfo'].esgProfileId;

            ctx.init();
        }

        // init logic
        private init(): ng.IPromise<any> {
            var ctx = this;

            ctx.isInitLoading = true;

            var def = ctx.$q.defer();

            var initPromise = super.initPage();


            // set EsgSummary view as the default view
            initPromise.then(
                // success
                function () {
                
                    ctx.hasEsgResearch = ctx.company.comprehensiveEsgResearchState === 2;
                    ctx.hasFocusRatings = ctx.company.coreEsgResearchState === 2;
                    ctx.hasControversiesResearch = ctx.company.controversyResearchState === 2;

                    if (!ctx.hasEsgResearch && !ctx.hasFocusRatings)
                    {
                        ctx.hasNoResearch = true;
                        if (ctx.company.comprehensiveEsgResearchState == Company.ResearchState.ResearchNotAvailable)
                            ctx.noResearchMessage = ctx.statusByResearchState(ctx.company.coreEsgResearchState);
                        else if (ctx.company.coreEsgResearchState == Company.ResearchState.ResearchNotAvailable)
                            ctx.noResearchMessage = ctx.statusByResearchState(ctx.company.comprehensiveEsgResearchState);
                    }
                          
                    var companyEsgUniverse_Promise = ctx.getCompanyInEsgResearchUniverse(ctx.company.id);
                    var companyControversies_Promise = ctx.getCompanyInControversiesUniverse(ctx.company.id);

                    ctx.$q.all([companyEsgUniverse_Promise, companyControversies_Promise]).then(
                        // success
                        function () {                            
                            ctx.$timeout(function () {
                                ctx.$scope.$apply(function () {

                                    //ctx.changeView(EsgViewNames.EsgSummary);
                                    ctx.changeView(ctx.getViewNames().EsgSummary);
                                    
                                    // get industry lead personnel
                                    ctx.getindustryLeadPersonnel().then(
                                        // success
                                        function () { def.resolve(); },
                                        // error
                                        function () { def.reject(); });
                                });
                            });

                            def.resolve();
                        },
                        // error
                        function (reason) {
                            def.reject(reason);
                        });

                },
                // error
                function (reason) {
                 
                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: Esg Controller -> Error initializing' });
                
                    def.reject(reason);
                });

            var promise = def.promise;

            promise['finally'](function () {
                ctx.isInitLoading = false;

                if (ctx.company != undefined) {
                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId,
                        'cookieDomain': 'none',
                        'name': 'globalAccess'
                    });

                    ga('globalAccess.set', 'dimension1', ctx.userId);

                    var dateNow = new Date();
                    var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
                    var gaObject: any = {
                        Date: dateNowString,
                        AccountId: ctx.accountId,
                        UserId: ctx.userId,
                        CompanyId: ctx.company.id
                    };

                    ga('globalAccess.send', {
                        'hitType': 'event',
                        'eventCategory': 'Research',
                        'eventAction': 'OnscreenESGRatingReport',
                        'eventLabel': JSON.stringify(gaObject)
                    });
                }
            });

            return promise;
        }


        //init Esg Research is in universe
        private getCompanyInEsgResearchUniverse(companyId): ng.IPromise<Company.CorporateDataExtendedDto> {
            var ctx = this;
            var def = ctx.$q.defer();

            ctx.CompanyService.getById(companyId, Common.AccountFeature.EsgRatingsOnlineReport)
                .then(
                function (company) {
                    ctx.hasEsgUniverse = company.data.isEnabled;
                    def.resolve(company);
                },
                function (reason) {
                    //if (reason.status !== 404 && reason.status !== 401) { }
                    def.reject(reason);
                });

            return def.promise;
        }

        //init Controversies is in universe
        private getCompanyInControversiesUniverse(companyId): ng.IPromise<Company.CorporateDataExtendedDto> {
            var ctx = this;
            var def = ctx.$q.defer();

            ctx.CompanyService.getById(companyId, Common.AccountFeature.Controversies)
                .then(
                function (company) {
                    ctx.hasControversiesUniverse = company.data.isEnabled;
                    def.resolve(company);
                },
                function (reason) {
                    //if (reason.status !== 404 && reason.status !== 401) { }
                    def.reject(reason);
                });

            return def.promise;
        }


        // init - get industry lead personnel
        private getindustryLeadPersonnel(): ng.IPromise<EsgIndustryLeadPersonnelDto> {
            var ctx = this;

            var promise = ctx.EsgIndustryLeadPersonnelService.get(ctx.company.id);

            promise.then(function (res) {
                ctx.$timeout(function () {
                    ctx.$scope.$apply(function () {
                        ctx.industryLeadPersonnel = res;
                    });
                });
            },() => {

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: Esg Controler -> Error loading Industry Lead' });
                });

            return promise;
        }

        private statusByResearchState(researchState: Company.ResearchState):string
        {
            if (researchState == Company.ResearchState.ResearchNotAvailable)
                return "Research not available.";
            if (researchState == Company.ResearchState.ResearchInProgress)
                return "Research in progress.";
            if (researchState == Company.ResearchState.FrameworkNotApplicable)
                return "Framework not applicable.";

            return "";
        }

        // change currently active view
        public changeView(viewName: string, selectedIndicator: KeyEsgIssueIndicatorDto = null): void {
            var ctx = this;

            ctx.$location.hash("");
            ctx.viewName = viewName;
            ctx.selectedIndicator = selectedIndicator;

            ga('create', 'UA-4379897-6', {
                'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.userId);

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': 'Onscreen-Report', 'eventAction': 'ESG-Tab', 'eventLabel': viewName
            });
        }

        public getViewNames(): any {
            var ctx = this;
            //return (ctx.hasFocusRatingResearch)?EsgViewNames;

            return !ctx.hasFocusRatings ? EsgViewNames : EsgFocusView;
        }


        public goToControversyIndicator(controversyIndicator: Controversies.ControversyIndicatorDto = null) {
            if (controversyIndicator) {

                this.$rootScope['selectedControversyIndicator'] = controversyIndicator;

                var path = this.$location.path();
                var newPath = path.replace(/esgRatings/gi, 'controversies');
                this.$location.path(newPath);
            }
        }

        public goToEventIndicator(controversyIndicator: Controversies.ControversyIndicatorDto = null, eventIndicator: Controversies.EventIndicatorDto = null) {

            if (controversyIndicator && eventIndicator) {

                this.$rootScope['selectedControversyIndicator'] = controversyIndicator;
                this.$rootScope['selectedEventIndicator'] = eventIndicator;

                var path = this.$location.path();
                var newPath = path.replace(/esgRatings/gi, 'controversies');
                this.$location.path(newPath);
            }
        }


        public IsESGCompanyReportDownloadEnabled(): boolean {
            var ctx = this;
            var result = true;


            if (!ctx.hasEsgUniverse || !ctx.hasEsgResearch) {
                result = false;
            }

            return result;
        }

        public IsFocusedRatingsReportDownloadEnabled(): boolean {
            var ctx = this;
            var result = true;

            if (!ctx.hasEsgUniverse || !ctx.hasFocusRatings) {
                result = false;
            }

            return result;
        }
        
        public downloadESGCompanyReport(isDefault: boolean, isSummaryReport: boolean) {
            var ctx = this;
            var now = new Date();

            var nameNoGuid = ctx.company.companyNameUrlFriendly.substring(0, ctx.company.companyNameUrlFriendly.length - 37); 
            var reportName = nameNoGuid + "_ESGRatingsReport_" + ('0' + now.getDate()).slice(-2) + ('0' + (1 + now.getMonth())).slice(-2) + now.getFullYear();

            if (isSummaryReport) {
                reportName = nameNoGuid + "_ESGSummaryReport_" + ('0' + now.getDate()).slice(-2) + ('0' + (1 + now.getMonth())).slice(-2) + now.getFullYear();
            }

            ctx.MostActiveReportService.addReport(ctx.company.id);

            var dateNow = new Date();
            var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
            var gaObject: any = {
                Date: dateNowString,
                AccountId: ctx.accountId,
                UserId: ctx.userId,
                CompanyId: ctx.company.id
            };
            
            var dateNow = new Date();
            var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
            var gaObject: any = {
                Date: dateNowString,
                AccountId: ctx.accountId,
                UserId: ctx.userId,
                CompanyId: ctx.company.id
            };
            
            if (isDefault) {
                var parameters = new EsgCompanyReportParametersDto();
                parameters.accountId = ctx.accountId;
                parameters.accountTier = ctx.accountTier;
                parameters.companyId = ctx.company.id;
                parameters.isSummaryReport = isSummaryReport;

                ctx.LongRunningTaskManagerService.runTask(reportName,
                    JSON.stringify(parameters),
                    LRTM.LongRunningTaskTypeEnum.ESGCompanyReportPDF, true, null);

                this.sendGoogleAnalyticsBeacon('Research', "PDFESGRatingReport default settings", JSON.stringify(gaObject));
            }

            if (!isDefault && ctx.accountTier !== 3){
                var modalInstance = ctx.$modal.open(
                    {
                        templateUrl: '/Views/Research/EsgRatings/Common/downloadReport_dialog.tpl.html',
                        controller: 'DownloadReportController',
                        size: 'lg',
                        backdrop: 'static',
                        resolve: {
                            companyId: () => ctx.company.id,
                            companyName: () => ctx.company.companyName
                        }
                    });

                modalInstance.result.then((parameters: EsgCompanyReportParametersDto) => {

                    ctx.LongRunningTaskManagerService.runTask(reportName,
                        JSON.stringify(parameters),
                        LRTM.LongRunningTaskTypeEnum.ESGCompanyReportPDF, true, null);


                    gaObject.ReferenceUniverse = parameters.referenceUniverseName;
                    gaObject.WeightMatrix = parameters.matrixName;
                    gaObject.ComparativeGroup = parameters.comparativeGroupName;

                    this.sendGoogleAnalyticsBeacon('Research', "PDFESGRatingReport custom settings", JSON.stringify(gaObject));

                    console.log(parameters);
                });
            }
        }

        private sendGoogleAnalyticsBeacon(eventCategory: string, eventAction: string, eventLabel: string) {
            var ctx = this;

            ga('create', 'UA-4379897-6', {
                'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.userId);

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': eventCategory, 'eventAction': eventAction, 'eventLabel': eventLabel
            });
        }
    }
    
    angular.module(esgRatingsModuleName).controller('EsgController',
        ['$rootScope', '$scope', '$q', '$timeout', '$location', 'RoutingService', 'CompanyService', 'EsgIndustryLeadPersonnelService', 'NumberUtilityService',
            'MostActiveReportService', 'LongRunningTaskManagerService', '$modal', EsgController ]);
} 